package com.rrkd.util;

import java.io.BufferedInputStream;  
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileNotFoundException;  
import java.io.FileOutputStream;
import java.io.IOException;  
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;  
import java.nio.ByteBuffer;  
import java.nio.MappedByteBuffer;  
import java.nio.channels.FileChannel;  
import java.nio.channels.FileChannel.MapMode;  
import java.util.ArrayList;
import java.util.List;


  
public class FileUtils { 
	
    public byte[] getContent(String filePath) throws IOException {  
        File file = new File(filePath);  
        long fileSize = file.length();  
        if (fileSize > Integer.MAX_VALUE) {  
            System.out.println("file too big...");  
            return null;  
        }  
        FileInputStream fi = new FileInputStream(file);  
        byte[] buffer = new byte[(int) fileSize];  
        int offset = 0;  
        int numRead = 0;  
        while (offset < buffer.length  
        && (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) {  
            offset += numRead;  
        }  
        // 确保所有数据均被读取  
        if (offset != buffer.length) {  
        throw new IOException("Could not completely read file "  
                    + file.getName());  
        }  
        fi.close();  
        return buffer;  
    }  
  
    /** 
     * the traditional io way 
     *  
     * @param filename 
     * @return 
     * @throws IOException 
     */  
    public static byte[] toByteArray(File file) throws IOException {  
  
    
  
        ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length());  
        BufferedInputStream in = null;  
        try {  
            in = new BufferedInputStream(new FileInputStream(file));  
            int buf_size = 1024;  
            byte[] buffer = new byte[buf_size];  
            int len = 0;  
            while (-1 != (len = in.read(buffer, 0, buf_size))) {  
                bos.write(buffer, 0, len);  
            }  
            return bos.toByteArray();  
        } catch (IOException e) {  
            e.printStackTrace();  
            throw e;  
        } finally {  
            try {  
                in.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
            bos.close();  
        }  
    }  
  
    /** 
     * NIO way 
     *  
     * @param filename 
     * @return 
     * @throws IOException 
     */  
    public static byte[] toByteArray2(File file) throws IOException {  
  
        
  
        FileChannel channel = null;  
        FileInputStream fs = null;  
        try {  
            fs = new FileInputStream(file);  
            channel = fs.getChannel();  
            ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());  
            while ((channel.read(byteBuffer)) > 0) {  
                // do nothing  
                // System.out.println("reading");  
            }  
            return byteBuffer.array();  
        } catch (IOException e) {  
            e.printStackTrace();  
            throw e;  
        } finally {  
            try {  
                channel.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
            try {  
                fs.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
    }  
  
    /** 
     * Mapped File way MappedByteBuffer 可以在处理大文件时，提升性能 
     *  
     * @param filename 
     * @return 
     * @throws IOException 
     */  
    @SuppressWarnings("resource")
	public static byte[] toByteArray3(File file) throws IOException {  
  
        FileChannel fc = null;  
        try {  
            fc = new RandomAccessFile(file, "r").getChannel();  
            MappedByteBuffer byteBuffer = fc.map(MapMode.READ_ONLY, 0,  
                    fc.size()).load();  
            byte[] result = new byte[(int) fc.size()];  
            if (byteBuffer.remaining() > 0) {  
                // System.out.println("remain");  
                byteBuffer.get(result, 0, byteBuffer.remaining());  
            }  
            return result;  
        } catch (IOException e) {  
            e.printStackTrace();  
            throw e;  
        } finally {  
            try {  
                fc.close(); 
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
    }  
    /**
     * 将文件读到字符串中
     * @param filename
     * @return
     */
    public static String readString3(File file)

    {

        String str="";

        try {

            FileInputStream in=new FileInputStream(file);

            // size  为字串的长度 ，这里一次性读完

            int size=in.available();

            byte[] buffer=new byte[size];

            in.read(buffer);

            in.close();

            str=new String(buffer,"utf-8");

        } catch (IOException e) {

            // TODO Auto-generated catch block

            return null;

        }

        return str;

    }
    /**
	 * 获得文件类型
	 * 
	 * @param fileName
	 * @return
	 */
	public static String getSuffix(String fileName) {
		String fileType = fileName.substring(fileName.lastIndexOf("."),
				fileName.length());
		return fileType;
	}
	
	/**对文件名进行排序
	 * @param file
	 * @return
	 */
	public static Object[] GetFileName(File file) {
		File[] files = file.listFiles();
		List<String> filelist = new ArrayList<String>();
		for (File f : files) {
			filelist.add(f.getPath());
		}
		
		Object obj[] = filelist.toArray();
		// 进行冒泡排序
		String fileName = "";
		try {
			
		} catch (Exception e) {
			// TODO: handle exception
		}
		for (int i = 1; i < obj.length; i++) {
			for (int j = 0; j < obj.length-i; j++) {
				// 获得当前文件名的数字
				
					if (Integer.valueOf(obj[j].toString().substring(
							obj[j].toString().lastIndexOf("-")+1,
							obj[j].toString().lastIndexOf(".temp"))) > Integer
							.valueOf(obj[j+1].toString().substring(
									obj[j+1].toString().lastIndexOf("-")+1,
									obj[j+1].toString().lastIndexOf(".temp")))){
						fileName=obj[j].toString();
						obj[j]=obj[j+1];
						obj[j+1]=fileName;
						
					}
				} 
		
				
			
		}
		return obj;
	}
    /**
	 * 文件合并
	 * 
	 * @param file
	 * @param srcPaths
	 */
	public static boolean merge(File file, String destPath,String filetype) {
		
		Object[] str= GetFileName(file);
		boolean mergeOK=false;
		String filename="";
		File[] files = new File[str.length];
		for(int i=0;i<files.length;i++){
			files[i]=new File(str[i].toString());
		}
		if (files != null) {
			filename = files[0].getName().substring(0,
					files[0].getName().lastIndexOf("-"));
			//filename = getSuffix(filename);// 合并后的文件名
			//destPath = destPath + File.separator + filename+filetype;
		}
		File destFile = new File(destPath);// 合并后的文件
		if(!destFile.exists()){
			destFile.mkdirs();//文件不存在创建文件路径
		}
		destPath=destPath + File.separator + filename+filetype;
		destFile=new File(destPath);//创建文件
		OutputStream out = null;
		BufferedOutputStream bos = null;

		InputStream in = null;// 输入字节流
		BufferedInputStream bis = null;
		byte[] bytes = new byte[1024 * 1024];
		try {
			out = new FileOutputStream(destFile);
			bos = new BufferedOutputStream(out);
			for (int i = 0; i < files.length; i++) {
				in = new FileInputStream(files[i]);
				bis = new BufferedInputStream(in);
				int len = -1;
				while ((len = bis.read(bytes)) != -1) {
					bos.write(bytes, 0, len);
				}
				bis.close();
				in.close();
			}
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {

			try {
				if (bos != null)
					bos.close();
				if (out != null)
					out.close();
				mergeOK=true;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		return mergeOK;
		
		
	}

	public static void deleteFile(String filepath){
		File file=new File(filepath);
		String [] templist=file.list();
		File temp=null;
		for(int i =0;i<templist.length;i++){
			temp=new File(filepath+File.separator+templist[i]);
			if(temp.isFile()){
				temp.delete();
			}
			if(temp.isDirectory()){
				deleteFile(templist[i]);
			}
		}
		if(file.list().length==0){
			file.delete();
		}
	}
	
	public static void deleteFiles(File file){
		List<File> listfiles=new ArrayList<File>();
		
		File[] files=file.listFiles();
		if (file.isDirectory()) {
			if (files != null || files.length != 0) {
				for (File subFile : files) {
					if (subFile.isDirectory()) {
						listfiles.add(subFile);
					} else {
						subFile.delete();
					}
				}
			}
			if (listfiles.size() > 0) {
				for (File subFile : listfiles) {
					deleteFiles(subFile);
				}
			}else{
				file.getParentFile().delete();
			}

		}else{
			file.delete();
		}
		
	}

	public static String CheckSM3andCrc(File file,String SM3Code,String crc) {
		String checkReult="";
		try {
			String sm3 = SM3.getFileSM3String(file);// 获得已传入的文件的sm3值，进行比对
			String filecontent = FileUtils.readString3(file);// 将文件读取为字符串，如果文件内容过大要进行分块传输
			String CRCS = CRC.CRC_CCITT_Kermit(filecontent);
			if (!SM3Code.equals(sm3) && !crc.equals(CRCS)) {

				checkReult= Status.getCheckFalse();// 验证不通过，需要重新发送,如果是分块传输

			} else {
				checkReult= Status.getCheckSuccess();
			}
		} catch (IOException e1) {

			System.out.println(e1.toString());

		}
		return checkReult;
	}
    public static void main(String[] args) {
		String test="E://tempFile";
		File file=new File(test);
		//deleteFile(file.listFiles());
	}
}  

